package dk.itu.samd.group2.tagapastry.messages;

import java.io.IOException;

import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.NodeHandle;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;
import dk.itu.samd.group2.tagapastry.Index;
import dk.itu.samd.group2.tagapastry.Tag;
import dk.itu.samd.group2.tagapastry.TagFactory;
import dk.itu.samd.group2.tagapastry.TagapastryImpl;

public class IndexRetractionRequestMsg extends TagapastryMsg {

	public static final short TYPE = 6;
	private static final long serialVersionUID = TYPE;
	
	public IndexRetractionRequestMsg(Tag tag, NodeHandle sender) {
		super(tag, sender);
	}

	public IndexRetractionRequestMsg(InputBuffer buf, Endpoint endpoint) throws IOException {
		super(buf, endpoint);
	}

	@Override
	public void execute(TagapastryImpl taga) {
		//System.out.println("Calling IndexRetractionRequestMsg...");
		Index index = taga.getIndex(tag);
		Tag parentTag = TagFactory.duplicateTagMinusExtension(tag);
		char childExtension = tag.getExtensionLastChar();
		IndexRetractionResponseMsg msg = new IndexRetractionResponseMsg(parentTag, taga.getNodeHandle(), index.getEntries(), childExtension);
		taga.send(msg);
		// TODO should not delete the entries here as this msg might fail!
		// should have another confirmation, maybe generalize IndexExpansionMS
		taga.removeIndex(tag);
	}

	@Override
	public short getType() {
		return TYPE;
	}
	
	@Override
	public void serialize(OutputBuffer buf) throws IOException {
		super.serialize(buf);
	}

	@Override
	public Id getRecepientId() {
		return tag.getId();
	}
	

}
